import type { FormInstance, SelectProps } from 'antd';
import { Button, Flex, Form, Input, Modal, Select } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import TemplateContainer from '@/components/Template/TemplateContainer';
import type { DragItemType } from '@/types/template';

const TemplatePage: React.FC = () => {
  const formRef = useRef<FormInstance>(null);
  const templateData = useRef<Record<string, DragItemType[]>>({});
  const [templateOptions, setTemplateOptions] = useState<
    SelectProps['options']
  >([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [template, setTemplate] = useState<DragItemType[]>([]);
  const handleShowModal = () => {
    setIsModalOpen(true);
  };
  const handleCloseModal = async () => {
    await formRef.current?.resetFields();
    setIsModalOpen(false);
  };
  const handleSubmit = async () => {
    const values = await formRef.current?.validateFields();
    const { name } = values;
    const localData = localStorage.getItem('templateData');
    let store = {} as Record<string, DragItemType[]>;
    if (localData) {
      store = JSON.parse(localData);
    }
    store[name] = template;
    localStorage.setItem('templateData', JSON.stringify(store));
    await formRef.current?.resetFields();
    setIsModalOpen(false);
  };
  const getTemplateList = async () => {
    const data = JSON.parse(localStorage.getItem('templateData') || '{}');
    templateData.current = data;
    const options = Object.keys(data).map((key) => ({
      label: key,
      value: key,
    }));
    setTemplateOptions(options);
  };
  const handleSelectChange = (value: string) => {
    if (!value) {
      setTemplate([]);
      return;
    }
    const template = templateData.current[value];
    setTemplate(template);
  };
  useEffect(() => {
    getTemplateList();
  }, []);
  return (
    <>
      <Flex gap="small" wrap style={{ marginBottom: '20px' }}>
        <Select
          allowClear
          showSearch
          style={{ width: 200 }}
          placeholder="请选择模板"
          options={templateOptions}
          onChange={handleSelectChange}
        ></Select>
        <Button type="primary" onClick={handleShowModal}>
          保存模板
        </Button>
      </Flex>
      <TemplateContainer
        type="edit"
        template={template}
        onTemplateChange={setTemplate}
      />
      <Modal
        title="保存模板"
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
      >
        <Form ref={formRef}>
          <Form.Item
            label="模板名称"
            name="name"
            rules={[{ required: true, message: '请输入模板名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default TemplatePage;
